package com.aloda.ojcommon.aspect;

import cn.hutool.core.bean.BeanUtil;
import com.aloda.ojcommon.constant.ErrorCode;
import com.aloda.ojcommon.context.UserBaseContext;
import com.aloda.ojcommon.domain.dto.UserCacheDTO;
import com.aloda.ojcommon.exception.AuthException;
import com.aloda.ojcommon.anno.AuthCheck;
import com.aloda.ojcommon.domain.enums.UserRoleEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限校验切面类
 *
 * @Author aloda
 * @Date 2025/4/27 10:18
 */
@Aspect
@Component
public class AuthAspect {

    /**
     * 管理端权限校验
     * @param joinPoint 切入点
     * @param authCheck 校验注解
     * @throws Throwable
     */
    @Before("@annotation(authCheck)")
    public void authCheck(JoinPoint joinPoint, AuthCheck authCheck) {
        // 获取校验权限
        List<UserRoleEnum> role = Arrays.stream(authCheck.role()).collect(Collectors.toList());
        // 获取当前登录用户
        UserCacheDTO user = UserBaseContext.getUser();
        if (BeanUtil.isEmpty(user)) {
            throw new AuthException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 如果没有权限抛出无权限异常
        if (!role.contains(UserRoleEnum.getEnumByRole(user.getUserRole()))) {
            throw new AuthException(ErrorCode.FORBIDDEN_ERROR);
        }
    }
}
